//
//  SendStatusViewController.swift
//  weibo
//
//  Created by cmh on 15/9/10.
//  Copyright © 2015年 cmh. All rights reserved.
//

import UIKit
import SVProgressHUD

private let XMYSendStatusLength  = 10

class SendStatusViewController: UIViewController, UITextViewDelegate {
    
    // MRAK: - 切换表情键盘
    /// 表情键盘控制器 － 注意：如果闭包中调用 self. 函数，同样会做 copy，需要注意循环引用
    private lazy var emoticonVC: EmoticonViewController = EmoticonViewController { [weak self](emoticon) -> () in
        
        // 插入表情
        self?.textView.insertEmoticon(emoticon)
        
        // 所有文字
//        self?.textView.tectViewAttributedText
        
    }
    
    // 切换表情键盘
    @objc private func switchEmoticonKeyboard() {
        
        // 关闭键盘
        textView.resignFirstResponder()
        
        // 切换表情键盘
        textView.inputView = (textView.inputView == nil) ? emoticonVC.view : nil
        
        // 开启键盘
        textView.becomeFirstResponder()
    
    }
    
    // 工具栏的约束
    private var toolbarBottomCons: NSLayoutConstraint?
    // 图片选择的约束
    private var upImageHeightCons: NSLayoutConstraint?
    // 文本视图的底部约束
    private var textViewBottomCons: NSLayoutConstraint?
    
    // 关闭控制器
    @objc private func closeController() {
        
        // 关闭键盘
        textView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    // 发送微博
    @objc private func sendStatus() {
        
        // 对过长的内容做提示
        let text = textView.tectViewAttributedText
        
        if text.characters.count > XMYSendStatusLength {
        
            SVProgressHUD.showInfoWithStatus("输入的内容过长", maskType: SVProgressHUDMaskType.Black)

        }
        
        
        printLog("发送微博")
    }
    
    // 添加照片
    @objc private func selectPicture() {
    
        // 删除textView和toolbar之间的约束
        view.removeConstraint(textViewBottomCons!)
        
        // 设置view和图片选择之间的约束
        textViewBottomCons = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: uploadImageVC.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 1)
        
        view.addConstraint(textViewBottomCons!)
        
        // 图片选择器的高度约束
        upImageHeightCons?.constant = UIScreen.mainScreen().bounds.height * 0.6
        
        // 关闭键盘
        textView.resignFirstResponder()
        
        // 更新约束
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    
    }
    
    // textView的代理方法
    func textViewDidChange(textView: UITextView) {
        
        placeholderLabel.hidden = textView.hasText()
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        // 设置提示标签的内容
        // 获取textView中文字的长度
        let len = XMYSendStatusLength - textView.tectViewAttributedText.characters.count
        
        lengthTipLabel.text = String(len)
        
        lengthTipLabel.textColor = (len > 0) ? UIColor.lightGrayColor() : UIColor.redColor()
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // 键盘的监听
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    // 注销通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - 监听键盘的改变
    @objc private func keyboardChange(n: NSNotification) {
        
        // 动画曲线
        let curve = n.userInfo![UIKeyboardAnimationCurveUserInfoKey]!.integerValue
        
        let rect = n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        // 动画时长，添加了动画曲线之后，这个时长就是摆设，没有用了
//        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        toolbarBottomCons?.constant = -UIScreen.mainScreen().bounds.height + rect.origin.y
        
        // 更新约束
        UIView.animateWithDuration(0.5) { () -> Void in
            
            // 设置动画曲线
            UIView.setAnimationCurve(UIViewAnimationCurve.init(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
        
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 只有用户没有选择照片的时候在激活键盘
        if upImageHeightCons?.constant == 0 {
            
            // 激活键盘
            textView.becomeFirstResponder()
        }
        
    }
    
    
    // 准备界面
    override func loadView() {
        
        view = UIView()
        
        view.backgroundColor = UIColor.whiteColor()
        
        addNavigationItem()
        prepareToolBar()
        prepareTextView()
        preparePictureView()
        
    }

    // MARK: - 准备页面布局
    // 准备图片选择器
    private func preparePictureView() {
    
        addChildViewController(uploadImageVC)
        
        // 插入视图
        view.insertSubview(uploadImageVC.view, belowSubview: toolbar)
        
        // 自动布局
        let size = UIScreen.mainScreen().bounds.size
        let w = size.width
        let h: CGFloat = 0
        
        let cons = uploadImageVC.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: w, height: h))
        
        upImageHeightCons = uploadImageVC.view.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)

    }
    
    // 准备导航条
    private func addNavigationItem() {
 
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "closeController")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        
        // 禁用发送按钮
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        
        let titleLabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 15)
        let nameLabel = UILabel(title: UserAccountViewModel.shareUserAccount.userAccount?.name, color: UIColor.lightGrayColor(), fontSize: 13)
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        // 设置布局
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        
        navigationItem.titleView = titleView
        
    }
    
    // 准备文本标签
    private func prepareTextView() {
        
        view.addSubview(textView)
        
        let dict: [String: AnyObject] = ["top": topLayoutGuide, "tb": toolbar, "tv": textView]
        
        // 设置自动布局
        textView.translatesAutoresizingMaskIntoConstraints = false
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tv]-0-|", options: [], metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[top]-0-[tv]", options: [], metrics: nil, views: dict))
        
        // 添加textView和工具栏之间的约束
        textViewBottomCons = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolbar, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        
        view.addConstraint(textViewBottomCons!)
        
        // 添加占位标签
        textView.addSubview(placeholderLabel)
        
        // 占位图片的frame
        placeholderLabel.frame = CGRect(origin: CGPoint(x: 8, y: 8), size: placeholderLabel.bounds.size)
        
        // 添加长度提示标签
        view.addSubview(lengthTipLabel)
        
        // 自动布局
        lengthTipLabel.ff_AlignInner(type: ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -statusCellMargin, y: -statusCellMargin))

    }
    
    // 准备工具栏
    private func prepareToolBar() {
        
        view.addSubview(toolbar)
        
        // 背景
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        // 设置自动布局
        let width = UIScreen.mainScreen().bounds.width
        
        let cons = toolbar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: width, height: 44))
        
        // 记录底部约束
        toolbarBottomCons = toolbar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        // 定义按钮数组
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action" : "switchEmoticonKeyboard"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["action"]))
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        toolbar.items = items  
    
    }

    // 懒加载文字控件
    private lazy var textView: UITextView = {
        
        let tv = UITextView()
        
        tv.delegate = self
        
        tv.font = UIFont.systemFontOfSize(18)
        
        tv.tintColor = UIColor.darkGrayColor()
        
        // 允许垂直滚动
        tv.alwaysBounceVertical = true
        
        // 拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
   
        return tv
      
    }()
    
    // 懒加载占位标签
    private lazy var placeholderLabel: UILabel = UILabel(title: "分享一些新鲜事...", color: UIColor.lightGrayColor(), fontSize: 18)
    
    // 懒加载tabbool控件
    private lazy var toolbar: UIToolbar = UIToolbar()
    
    // 懒加载图片选择器
    private lazy var uploadImageVC: UploadImageController = UploadImageController()
    
    // 懒加载长度提示标签
    private lazy  var lengthTipLabel: UILabel = UILabel(title: "", color: UIColor.lightGrayColor(), fontSize: 15)

 }
